﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using CqCore.Logging;
using CqCore.SMS;
using SMS.Options;

namespace SMS.Services
{
    public class SMSService : ISMSService
    {
        private readonly ILogRecorder<SMSService> logRecorder;
        private readonly SmsOption smsOption;

        public SMSService(ILogRecorder<SMSService> logRecorder, SmsOption smsOption)
        {
            this.logRecorder = logRecorder;
            this.smsOption = smsOption;
        }

        public int Send_YYDZ_Code(string phone, string code)
        {
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", smsOption.AccessKeyId, smsOption.Secret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action = "SendSms";
            // request.Protocol = ProtocolType.HTTP;
            request.AddQueryParameters("PhoneNumbers", phone);
            request.AddQueryParameters("SignName", smsOption.SignName);
            request.AddQueryParameters("TemplateCode", smsOption.TemplateCode);
            request.AddQueryParameters("TemplateParam", "{\"code\":\"" + code + "\"}");
            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                return response.Data.Contains("OK") ? 200 : -1;
                //Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
            }
            catch (ServerException e)
            {
                logRecorder.Error(new EventData()
                {
                    Type = "SMSService.Add.Send_YYDZ_Code",
                    Message = "优越店长短信验证码",
                    Labels = {
                        ["Error"]=e.Message
                    }
                });
                return -1;
            }
        }
    }
}
